using System.Collections.Generic;

namespace ET
{

    //提供给 ILruntime 使用的  不跨域继承
    public class MultiMap<T, K>
    {
        private readonly List<K> Empty = new List<K>();
        private SortedDictionary<T, List<K>> SortedDic = new SortedDictionary<T, List<K>>();


        public int Count => SortedDic.Count;
        public void Add(T t, K k)
        {
            List<K> list;
            SortedDic.TryGetValue(t, out list);
            if (list == null)
            {
                list = new List<K>();
                SortedDic.Add(t, list);
            }
            list.Add(k);
        }


        public bool Remove(T t, K k)
        {
            List<K> list;
            SortedDic.TryGetValue(t, out list);
            if (list == null)
            {
                return false;
            }
            if (!list.Remove(k))
            {
                return false;
            }
            if (list.Count == 0)
            {
                SortedDic.Remove(t);
            }
            return true;
        }



        /// <summary>
        /// 不返回内部的list,copy一份出来
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public K[] GetAll(T t)
        {
            List<K> list;
            SortedDic.TryGetValue(t, out list);
            if (list == null)
            {
                return new K[0];
            }
            return list.ToArray();
        }

        /// <summary>
        /// 返回内部的list
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public List<K> this[T t]
        {
            get
            {
                SortedDic.TryGetValue(t, out List<K> list);
                return list ?? Empty;
            }
        }

        public K GetOne(T t)
        {
            List<K> list;
            SortedDic.TryGetValue(t, out list);
            if (list != null && list.Count > 0)
            {
                return list[0];
            }
            return default;
        }

        public bool Contains(T t, K k)
        {
            List<K> list;
            SortedDic.TryGetValue(t, out list);
            if (list == null)
            {
                return false;
            }
            return list.Contains(k);
        }




        //以下为 兼容方法


        public bool Remove(T t)
        {
            bool bol = SortedDic.ContainsKey(t);
            SortedDic.Remove(t);
            return bol;
        }

        public void Clear() 
        {
            SortedDic.Clear();
        }

        public SortedDictionary<T, List<K>>.KeyCollection Keys => SortedDic.Keys;
        public SortedDictionary<T, List<K>>.ValueCollection Values => SortedDic.Values;
        public SortedDictionary<T, List<K>> Foreach => SortedDic;//只循序 Foreach 使用这个属性
    }
}
